package com.lxl.priv.bak;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author Administrator
 */
public class MultiThreadProcessor {

    private static final int THREAD_COUNT = 10; // 假设使用4个线程
    private static CSVPrinter csvPrinter;

    public static void processData(List<String> dataItems) {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);

        try {
            int dataPerThread = dataItems.size() / THREAD_COUNT;
            for (int i = 0; i < THREAD_COUNT; i++) {
                final int start = i * dataPerThread;
                final int end = (i == THREAD_COUNT - 1) ? dataItems.size() : (i + 1) * dataPerThread;
                Future<?> future = executorService.submit(() -> {
                    for (int j = start; j < end; j++) {
                        processItem(dataItems.get(j)); // 处理单个数据项
                    }
                });
                // 可以在这里处理Future的结果或检查异常
            }
        } finally {
            executorService.shutdown(); // 关闭线程池，不再接受新任务，已提交的任务将继续执行完毕
            // 可以在这里添加等待所有任务完成的逻辑，如 executorService.awaitTermination(...)
        }
    }

    private static void processItem(String item) {
        // 处理单个数据项的逻辑
        try {
            csvPrinter.printRecords(item);
            csvPrinter.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        // 示例数据
        for (int i = 0; i < 100; i++) {
            list.add(String.valueOf(i));
        }
        long start = System.currentTimeMillis();
        try {
            csvPrinter = new CSVPrinter(new BufferedWriter(new FileWriter("D://test.csv")),
                    CSVFormat.DEFAULT);
        } catch (IOException e) {
            System.out.println("创建失败");
        }
        processData(list);
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start) + "ms");
    }
}
